<template>
  <div>
    <h2>人员信息录入</h2>
    <!-- 人员信息录入表单 -->
    <el-form :model="userForm">
      <!-- 姓名输入框 -->
      <el-form-item label="姓名">
        <el-input v-model="userForm.name"></el-input>
      </el-form-item>
      <!-- 年龄输入框 -->
      <el-form-item label="年龄">
        <el-input v-model="userForm.age"></el-input>
      </el-form-item>
      <!-- 身份证号输入框 -->
      <el-form-item label="身份证号">
        <el-input v-model="userForm.idCard"></el-input>
      </el-form-item>
      <!-- 证件照片上传 -->
      <el-form-item label="证件照片">
        <el-upload
            class="avatar-uploader"
            action="https://jsonplaceholder.typicode.com/posts/"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
          <img v-if="userForm.photoUrl" :src="userForm.photoUrl" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <div class="registration-container">
        <h2>人脸录入</h2>
        <div class="video-container">
          <video ref="video" width="640" height="480" autoplay></video>
          <button @click="captureAndRegister">录入人脸</button>
        </div>
      </div>
      <!-- 保存按钮 -->
      <el-form-item>
        <el-button type="primary" @click="saveUser">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import router from '@/router'
import axios from 'axios';

export default {
  setup() {
    const video = ref(null);
    const userForm = ref({
      name: '',
      age: '',
      idCard: '',
      photoUrl: ''
    });

    onMounted(() => {
      if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
        navigator.mediaDevices.getUserMedia({ video: true })
            .then(stream => {
              video.value.srcObject = stream;
            })
            .catch(error => {
              console.error('Error accessing webcam:', error);
            });
      }
    });

    // 处理头像上传成功事件
    const handleAvatarSuccess = (response, file) => {
      userForm.value.photoUrl = URL.createObjectURL(file.raw);
    };

    // 头像上传前的验证
    const beforeAvatarUpload = (file) => {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        alert('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        alert('上传头像图片大小不能超过 2MB!');
      }

      return isJPG && isLt2M;
    };

    // 捕获视频帧并注册人脸
    const captureAndRegister = async () => {
      if (!video.value) return;

      const canvas = document.createElement('canvas');
      canvas.width = video.value.videoWidth;
      canvas.height = video.value.videoHeight;
      const context = canvas.getContext('2d');
      context.drawImage(video.value, 0, 0, canvas.width, canvas.height);
      const imageBase64 = canvas.toDataURL('image/jpeg').split(',')[1];

      try {
        const response = await axios.post('http://127.0.0.1:5000/face-register', {
          staff_id: userForm.value.idCard,
          image: imageBase64
        }, { headers: { 'Content-Type': 'application/json' } });

        if (response.status === 200) {
          alert('人脸录入成功！');
          router.push('/index');
        } else {
          alert('人脸录入失败，请重试！');
        }
      } catch (error) {
        console.error('Error during face registration:', error.message);
        alert('人脸录入失败，请重试！');
      }
    };

    // 保存用户信息
    const saveUser = async () => {
      try {
        const response = await axios.post('http://localhost:8083/add-user', {
          name: userForm.value.name,
          age: userForm.value.age,
          idCard: userForm.value.idCard,
          photoUrl: userForm.value.photoUrl
        });

        if (response.status === 201) {
          alert('用户信息录入成功！');
          router.push({ name: 'userManagement' });
        } else {
          alert('用户信息录入失败，请重试！');
        }
      } catch (error) {
        console.error('Error saving user information:', error.message);
        alert('用户信息录入失败，请重试！');
      }
    };

    return {
      video,
      userForm,
      handleAvatarSuccess,
      beforeAvatarUpload,
      captureAndRegister,
      saveUser
    };
  }
};
</script>


<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
video {
  margin-top: 10px;
}
</style>